/**
 * @name: testRoute
 * @author: XU>.<CHEN
 * @date: 2022-05-24 21:21
 * @description：testRoute
 * @update: 2022-05-24 21:21
 */
import { Router, Request, Response } from "express";
import jwt from 'jsonwebtoken'

import ResponseMessage from "../utils/ResponseMessage";
import db from "../db/config";

const user:Router = Router()
const R = new ResponseMessage()
const secretOrPublicKey = 'blackSide' // jwt加密盐值


// @RequestMapping(value = '/user')


/**
 * @登录接口
 */
user.post('/login', (req, res) => {
  const { userName, password } = req.body
  const sql = `
    SELECT 
      USER_NAME as userName, 
      PASSWORD as password,
      REAL_NAME as realName,
      PHONE_NUM as phoneNum,
      EMAIL as email
    FROM T_USER_INFO WHERE USER_NAME = ? AND PASSWORD = ? LIMIT 1;
  `
  db.query(sql, [userName, password], (err: any, result: any) => {
    if (result && result.length) {
      const token = `${jwt.sign({...result[0]}, 'blackSide', {expiresIn: 3600 * 24 * 7})}`
      res.json(R.success({
        userInfo: result[0],
        token: token
      }))
    } else {
      res.json(R.error('用户名或密码错误'))
    }
  })
})

/**
 * @注册接口
 */
user.post('/register', (req, res) => {
  const { userName, password } = req.body
  const sql = `INSERT INTO T_USER_INFO(USER_NAME,PASSWORD,REAL_NAME) values (?,?,?)`
  db.query(sql, [userName, password, userName], (err: any, result: any) => {
    res.json(R.success(1001))
  })
})

/**
 * @获取登录用户菜单权限接口
 */
user.get('/getRouteAuth', (req, res) => {
  // @ts-ignore
  const userName: string | null = globalThis.userInfo.userName
  const getMenuAuthSql = `SELECT MENU_AUTH as menuAuth FROM T_MENU_AUTH where USER_NAME = ?`
  const getMenuAuthListSql = `
    SELECT 
      ID as id,
      PID as pid,
      MENU_NAME as menuName,
      MENU_PATH as menuPath,
      COMPONENT_PATH as componentPath,
      LINK as link,
      REMARK as remark
    FROM T_MENU WHERE FIND_IN_SET(id,?)
  `
  db.query(getMenuAuthSql, [userName], (err: any, result: any) => {
    if (result && result.length) {
      const menuAuth = result[0].menuAuth
      db.query(getMenuAuthListSql, [menuAuth], (err: any, authResult: any) => {
        res.json(R.success(authResult || []))
      })
    } else {
      res.json(R.success([]))
    }
  })
})

/**
 * @获取登录用户菜单权限接口
 */
user.get('/getCurrent', (req, res) => {
  // @ts-ignore
  const userName: string | null = globalThis.userInfo.userName
  if (userName) {
    const sql = `
      SELECT 
        USER_NAME as userName,
        PASSWORD as password,
        REAL_NAME as realName,
        PHONE_NUM as phoneNum,
        EMAIL as email
      FROM T_USER_INFO WHERE USER_NAME = ?`
    db.query(sql, [userName], (err: any, result: any) => {
      if (result && result.length) {
        res.json(R.success(result[0]))
      } else {
        res.json(R.error('用户不存在'))
      }
    })
  } else {
    res.json(R.error('请登录'))
  }
})

export default user